package de.klingbeil.hhcalc.ui.application;

import com.vaadin.data.Item;
import com.vaadin.data.validator.IntegerValidator;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;

public class ItemFieldFactory extends DefaultFieldFactory {

	private static final long serialVersionUID = 1L;
	private static final String COMMON_FIELD_WIDTH = "12em";

	@Override
	public Field createField(Item item, Object propertyId, Component uiContext) {
		Field f;
		if ("password".equals(propertyId)) {
			// Create a password field so the password is not shown
			f = createPasswordField(propertyId);
		} else {
			// Use the super class to create a suitable field base on the
			// property type.
			f = super.createField(item, propertyId, uiContext);
		}

		if ("firstName".equals(propertyId)) {
			TextField tf = (TextField) f;
			tf.setRequired(true);
			tf.setRequiredError("Please enter a First Name");
			tf.setWidth(COMMON_FIELD_WIDTH);
			tf.addValidator(new StringLengthValidator(
					"First Name must be 3-25 characters", 3, 25, false));
		} else if ("lastName".equals(propertyId)) {
			TextField tf = (TextField) f;
			tf.setRequired(true);
			tf.setRequiredError("Please enter a Last Name");
			tf.setWidth(COMMON_FIELD_WIDTH);
			tf.addValidator(new StringLengthValidator(
					"Last Name must be 3-50 characters", 3, 50, false));
		} else if ("password".equals(propertyId)) {
			PasswordField pf = (PasswordField) f;
			pf.setRequired(true);
			pf.setRequiredError("Please enter a password");
			pf.setWidth("10em");
			pf.addValidator(new StringLengthValidator(
					"Password must be 6-20 characters", 6, 20, false));
		} else if ("shoesize".equals(propertyId)) {
			TextField tf = (TextField) f;
			tf.setNullRepresentation("");
			tf.setNullSettingAllowed(true);
			tf.addValidator(new IntegerValidator("Shoe size must be an Integer"));
			tf.setWidth("4em");
		}

		return f;
	}

	private PasswordField createPasswordField(Object propertyId) {
		PasswordField pf = new PasswordField();
		pf.setCaption(DefaultFieldFactory.createCaptionByPropertyId(propertyId));
		return pf;
	}
}